/*
  操作dom的公用方法
*/
import { FileUrl } from 'api/config'

// 下载或预览一个文件
export const downLoadFile = (file, options = {}) => {
  if (typeof file === 'object' && Array.isArray(file)) {
    const { nameKey = 'filePath' } = options
    file.map(item => {
      window.open(`${FileUrl}${item[nameKey]}`, '_blank')
    })
  } else {
    window.open(`${FileUrl}${file}`, '_blank')
  }
}

/**
 * quality 图片质量
 */
export const downloadImg = (data, quality = 1) => {
  const { file_path, name } = data

  const url = `${FileUrl}${file_path}`

  pathToBase64(url, quality).then(res => {
    const link = document.createElement('a')
    link.href = res
    link.setAttribute('download', name)
    document.body.appendChild(link)
    link.click()
    link.remove()
  }).catch(err => {
    console.log(err)
  })
}

// 获取Base64且压缩图片
function pathToBase64 (url, quality = 1, width = 1, height = 1) {
  return new Promise((resolve, reject) => {
    let image = new Image()
    image.onload = function () {
      let canvas = document.createElement('canvas')
      canvas.width = image.width / width
      canvas.height = image.height / height
      canvas.getContext('2d').drawImage(image, 0, 0)
      let result = canvas.toDataURL('image/jpeg', quality)
      resolve(result)
    }
    image.setAttribute('crossOrigin', 'Anonymous')
    image.src = url
    image.onerror = () => {
      reject(new Error('urlToBase64 error'))
    }
  })
}

export const downloadPdf = (data) => {
  const { file_path, name } = data
  const url = `${FileUrl}${file_path}`

  fetch(url, {
    method: 'get',
    mode: 'cors'
  }).then((response) => response.blob()).then((res) => {
    const downloadUrl = window.URL.createObjectURL(
      // new Blob() 对后端返回文件流类型处理
      new Blob([res], {
        type: data.type == 'application/pdf'
      })
    )
    // word文档为msword,pdf文档为pdf
    const link = document.createElement('a')
    link.href = downloadUrl
    link.setAttribute('download', name)
    document.body.appendChild(link)
    link.click()
    link.remove()
  }).catch((error) => {
    console.log(error)
  })
}

// 获取body的宽度
export function getBodyWidth () {
  return getWidth(document.getElementsByTagName('body')[0])
}

// 获取body的高度
export function getBodyHeight () {
  return getHeight(document.getElementsByTagName('body')[0])
}

// 获取元素的宽度
export function getWidth (el) {
  return el.clientWidth
}

// 获取元素的高度
export function getHeight (el) {
  return el.clientHeight
}

// 获取浏览器query参数
export function getRequest () {
  var url = location.href.split('?')[1]
  var theRequest = {}

  if (url) {
    var strs = url.split('&')
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
    }
  }

  return theRequest
}

export const getScrollWidth = () => {
  const odiv = document.createElement('div') // 创建一个div
  const styles = {
    width: '100px',
    height: '100px',
    position: 'fixed',
    bottom: '-10000px',
    overflowY: 'scroll' // 让他有滚动条
  }

  for (var i in styles) odiv.style[i] = styles[i]
  document.body.appendChild(odiv) // 把div添加到body中
  const scrollbarWidth = odiv.offsetWidth - odiv.clientWidth // 相减
  odiv.remove() // 移除创建的div

  return scrollbarWidth
}

// 阻止冒泡事件兼容写法
export const CancelBubble = (event) => {
  if (event.stopPropagation) {
    event.stopPropagation()
  } else {
    event.cancelBubble = true
  }
}

// 取消默认事件兼容
export const returnFalse = (event) => {
  if (event.preventDefault) {
    event.preventDefault()
  } else {
    window.event.returnValue = false
  }
  return false
}

// 创建Html的标签
export const createHtml = (name) => document.createElement(name)
